package com.fjnu.interceptor;

import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjnu.controller.LoginController;
import com.fjnu.entities.User;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger =LogManager.getLogger(LoginInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		User user=(User) request.getSession().getAttribute("user");
		if(user!=null) 
			return true;
		Map<String , Object> data = new HashMap<String, Object>();
		data.put("status", "fail");
		data.put("cause", "请先登录");
		logger.debug(data);
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(data);
		response.setCharacterEncoding("utf-8");
		Writer writer = new OutputStreamWriter(response.getOutputStream());
		writer.write(jsonString);
		writer.flush();
		return false;
	}
	
}
